package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.UserAuthConstants;
import com.heima.feign.wemedia.IWemediaClient;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserCheckMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserCheckService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @Auther: Tangguo
 * @Date: 2023-06-21  08:56
 */

@Service
@Slf4j
@Transactional
public class ApUserCheckServiceImpl extends ServiceImpl<ApUserCheckMapper, ApUserRealname> implements ApUserCheckService {

    @Autowired
    private ApUserMapper apUserMapper;


    @Autowired
    private IWemediaClient wemediaClient;
    /**
     * 可根据审核状态条件查询用户列表
     * @param dto :
     * @return ResponseResult
     */
    @Override
    public ResponseResult loadUserList(AuthDto dto) {
        //1.参数校验
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.构建分页查询条件
        IPage page=new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper=new LambdaQueryWrapper();

        //3.可根据审核状态条件查询
        if(dto.getStatus()!=null){
            wrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }

        //4.分页查询
        page(page,wrapper);

        //5.返回结果
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    /**
     * 审核更新状态
     * @param dto :
     * @return ResponseResult
     */
    @Override
    public ResponseResult authWithUpdateStatus(AuthDto dto,Short status) {
        //1.参数校验
        if(dto==null||dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.业务处理
        ApUserRealname apUserRealname=new ApUserRealname();
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(status);

        //如果存在违规内容则驳回（状态改为2，文章审核失败）
        if(StringUtils.isNotBlank(dto.getMsg())){
            //设置拒绝原因
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);

        //用户通过审核后需要开通自媒体账号（该账号的用户名和密码与app一致）
        if(status.equals(UserAuthConstants.AUTH_PASS)){
            ResponseResult result=creatWemediaAccount(dto);
            if(result!=null){
                return result;
            }

        }
        //3.返回结果
       return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 创建自媒体账号
     * @param :
     * @return void
     */
    private ResponseResult creatWemediaAccount(AuthDto dto) {
        //1.校验该账号的用户名和密码与app是否一致
        //1.1查询用户认证信息
        ApUserRealname apUserRealname =getById(dto.getId());
        if(apUserRealname==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到该用户认证信息");
        }
        //1.2查询app用户信息
        //获取账号id
        Integer userId = apUserRealname.getUserId();
        //根据账号id查询app用户
        ApUser apUser = apUserMapper.selectById(userId);
        if(apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到该用户app端用户信息");
        }
        //远程调用接口，创建自媒体账号
        WmUser wmUser = wemediaClient.findWmUserByName(apUser.getName());

        if(wmUser == null){
            wmUser= new WmUser();
            wmUser.setApUserId(apUser.getId());
            wmUser.setCreatedTime(new Date());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setStatus(9);
            wemediaClient.saveWmUser(wmUser);
        }
        apUser.setFlag((short)1);
        apUserMapper.updateById(apUser);

        return null;
    }


}
